﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ParsecParser;
using ParsecParser.Communication;
using ParsecParser.Data;
using ParsecParser.Display;
using ParsecParser.Helpers;
using ParsecClient.Classes;
using Microsoft.Win32;

namespace ParsecClient
{
    /// <summary>
    /// Interaction logic for ImportWindow.xaml
    /// </summary>
    public partial class ImportWindow : Window
    {
        public ImportWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //mark all checks
                chkCharacter.IsChecked = true;
                chkRaidGroups.IsChecked = true;
                chkSettings.IsChecked = true;
                chkTimers.IsChecked = true;
                chkTimersRemove.IsChecked = true;
                chkCharacterRemove.IsChecked = true;
                chkRaidGroupsRemove.IsChecked = true;

                //set default export file name
                txtFilePath.Text = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "ParsecSettingsExport.xml");
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error Loading Import", "Error on Window_Loaded", ex, this, true);
            }
        }
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Debug.WriteLine("Load Button Clicked");
                OpenFileDialog openFileDialog = new OpenFileDialog();
                string currentPath = null;
                if (!string.IsNullOrEmpty(txtFilePath.Text))
                {
                    try
                    {
                        currentPath = System.IO.Path.GetDirectoryName(txtFilePath.Text);
                    }
                    catch
                    {
                        currentPath = null;
                    }
                }
                if (!string.IsNullOrEmpty(currentPath) && System.IO.Directory.Exists(currentPath))
                    openFileDialog.InitialDirectory = currentPath;
                else
                    openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                openFileDialog.RestoreDirectory = true;
                openFileDialog.DefaultExt = "xml";
                openFileDialog.AddExtension = true;
                openFileDialog.FileName = System.IO.Path.GetFileName(txtFilePath.Text);
                openFileDialog.CheckFileExists = false;
                openFileDialog.Filter = "XML files (*.xml)|*.xml";
                openFileDialog.Title = "Import File Path";
                bool? result = openFileDialog.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    txtFilePath.Text = openFileDialog.FileName;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnBrowse_Click", ex, this, true);
            }
        }
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnCancel_Click", ex, this, true);
                this.Close();
            }
        }
        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtFilePath.Text) || !System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtFilePath.Text)))
                {
                    ((App)Application.Current).HandleError("Invalid Export Path", null, null, this, false);
                }
                else
                {
                    ParsecDataExport export = null;
                    try
                    {
                        export = ParsecDataExport.ReadExportFile(txtFilePath.Text);
                    }
                    catch (Exception ex)
                    {
                        ((App)Application.Current).HandleError("Error Reading File", null, ex, this, true);
                        return;
                    }
                    if (export == null)
                    {
                        ((App)Application.Current).HandleError("Error Reading File", null, null, this, false);
                        return;
                    }

                    if (chkCharacter.IsChecked ?? false)
                    {
                        if (export.CharacterSettings != null && export.CharacterSettings.CharacterSettings != null && export.CharacterSettings.CharacterSettings.Count > 0)
                        {
                            //settings in file
                            if (chkCharacterRemove.IsChecked ?? false)
                            {
                                ((App)Application.Current).AllCharacterSettings = CharacterSettingsCollection.SaveAllCharacterSettings(export.CharacterSettings.CharacterSettings);
                            }
                            else
                            {
                                //collisions are ignored
                                var okSettings = export.CharacterSettings.CharacterSettings.Where(x => ((App)Application.Current).AllCharacterSettings.FirstOrDefault(y => y.CharacterName == x.CharacterName) == null).ToList();
                                foreach (var s in okSettings)
                                {
                                    CharacterSettingsCollection.SaveCharacterSettings(s);
                                }
                                ((App)Application.Current).AllCharacterSettings = CharacterSettingsCollection.RetrieveCharacterSettings();
                            }
                        }
                        else
                        {
                            //settings not in file
                            if (chkCharacterRemove.IsChecked ?? false)
                            {
                                //remove existing
                                CharacterSettingsCollection.DeleteAllCharacterSettings();
                                ((App)Application.Current).AllCharacterSettings = CharacterSettingsCollection.RetrieveCharacterSettings();
                            }
                        }
                    }
                    if (chkTimers.IsChecked ?? false)
                    {
                        if (export.TimerDefs != null && export.TimerDefs.Timers != null && export.TimerDefs.Timers.Count > 0)
                        {
                            if (chkTimersRemove.IsChecked ?? false)
                            {
                                //replace all timers
                                TimerDefinitionCollection.DeleteAllTimerDefinition();
                                ((App)Application.Current).SetTimerDefinitions(export.TimerDefs.Timers);
                                TimerDefinitionCollection.SaveTimerDefinitions(((App)Application.Current).GetTimerDefinitions());
                            }
                            else
                            {
                                //merge timers
                                var currentTDs =((App)Application.Current).GetTimerDefinitions();
                                var okTimers = export.TimerDefs.Timers.Where(x => currentTDs.FirstOrDefault(y => string.CompareOrdinal(y.Description, x.Description) == 0) == null).ToList();
                                foreach (var t in okTimers)
                                {
                                    ((App)Application.Current).AddTimerDefinition(t);
                                }
                                TimerDefinitionCollection.SaveTimerDefinitions(((App)Application.Current).GetTimerDefinitions());
                            }
                        }
                        else
                        {
                            if (chkTimersRemove.IsChecked ?? false)
                            {
                                TimerDefinitionCollection.DeleteAllTimerDefinition();
                                ((App)Application.Current).SetTimerDefinitions(TimerDefinition.GetDefaults());
                                TimerDefinitionCollection.SaveTimerDefinitions(((App)Application.Current).GetTimerDefinitions());
                            }
                        }
                        ((ParsecWindow)((App)Application.Current).MainWindow).BindTimerDefinitions();
                    }
                    if (chkRaidGroups.IsChecked ?? false)
                    {
                        if (export.RaidGroups != null && export.RaidGroups.Count > 0)
                        {
                            if (chkRaidGroupsRemove.IsChecked ?? false)
                            {
                                //replace Raid Groups
                                ((App)Application.Current).RaidGroups = export.RaidGroups;
                                ParsecClient.Properties.Settings.Default.RaidGroups = export.RaidGroups.Serialize();
                                ParsecClient.Properties.Settings.Default.Save();
                            }
                            else
                            {
                                //merge Raid Groups
                                var okRaidGroups = export.RaidGroups.Where(x => ((App)Application.Current).RaidGroups.FirstOrDefault(y => string.CompareOrdinal(y.Name, x.Name) == 0) != null).ToList();
                                foreach (var g in okRaidGroups)
                                {
                                    ((App)Application.Current).RaidGroups.Add(g);
                                }
                                ParsecClient.Properties.Settings.Default.RaidGroups = ((App)Application.Current).RaidGroups.Serialize();
                                ParsecClient.Properties.Settings.Default.Save();
                            }
                        }
                        else
                        {
                            if (chkRaidGroupsRemove.IsChecked ?? false)
                            {
                                //delete all raidgroups
                                ParsecClient.Properties.Settings.Default.RaidGroups = (new List<RaidGroup>()).Serialize();
                                ParsecClient.Properties.Settings.Default.Save();
                            }
                        }
                        ((ParsecWindow)((App)Application.Current).MainWindow).BindRaidGroups();
                    }
                    if (chkSettings.IsChecked ?? false)
                    {
                        if (export.SettingsExported)
                        {
                            ParsecClient.Properties.Settings.Default.CombatLogFolder = export.CombatLogFolder;
                            ParsecClient.Properties.Settings.Default.ShowFilters = export.ShowFilters;
                            ParsecClient.Properties.Settings.Default.MainWindowHeight = export.MainWindowHeight;
                            ParsecClient.Properties.Settings.Default.MainWindowWidth = export.MainWindowWidth;
                            ParsecClient.Properties.Settings.Default.MainWindowTop = export.MainWindowTop;
                            ParsecClient.Properties.Settings.Default.MainWindowLeft = export.MainWindowLeft;
                            ParsecClient.Properties.Settings.Default.LastUsedRaidKey = export.LastUsedRaidKey;
                            ParsecClient.Properties.Settings.Default.MainTopMost = export.MainTopMost;
                            ParsecClient.Properties.Settings.Default.IsStreamMode = export.IsStreamMode;
                            ParsecClient.Properties.Settings.Default.IsSoftwareRenderingMode = export.IsSoftwareRenderingMode;
                            ParsecClient.Properties.Settings.Default.MainOpacity = export.MainOpacity;
                            ParsecClient.Properties.Settings.Default.RecentFiles = export.RecentFiles;
                            ParsecClient.Properties.Settings.Default.TimerVolume = export.TimerVolume;
                            ParsecClient.Properties.Settings.Default.DefaultTimeServer = export.DefaultTimeServer;
                            ParsecClient.Properties.Settings.Default.EnableTimeSync = export.EnableTimeSync;
                            ParsecClient.Properties.Settings.Default.TimeServerHostName = export.TimeServerHostName;
                            ParsecClient.Properties.Settings.Default.TimeServerPort = export.TimeServerPort;
                            if (!string.IsNullOrEmpty(export.RaidDetailsSortKey))
                                ParsecClient.Properties.Settings.Default.RaidDetailsSortKey = export.RaidDetailsSortKey;
                            ParsecClient.Properties.Settings.Default.Save();
                            ((App)Application.Current).LoadSystemSettings();
                            ((App)Application.Current).LoadWindowSettings();
                            ((App)Application.Current).RestartTimeSync();
                            ((App)Application.Current).UpdateTimeSync(true);
                            ((ParsecWindow)((App)Application.Current).MainWindow).BindRecentFiles();
                        }
                    }
                    this.Close();
                    ((App)Application.Current).HandleMessage("Import Completed Successfully", null);
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnImport_Click", ex, this, true);
            }
        }
    }
}
